<!--
 * @Description:
 * @Date: 2024-06-25 21:24:10
 * @LastEditTime: 2024-10-16 11:14:23
-->
<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '反馈信息填写',
  },
}
</route>
<template>
  <view class="bg-white overflow-hidden w-100% h-screen box-border overflow-auto">
    <view>
      <wd-notice-bar color="#029669" background-color="#f0f9eb">
        <template #prefix>
          <wd-icon size="20px" name="sound">占位符</wd-icon>
        </template>
        如实填写完成提交后，可在【我的-我上报的村情】功能处查看处理进度I
      </wd-notice-bar>
    </view>
    <view>
      <wd-form ref="form" :model="model" :rules="rules">
        <wd-cell title="标题" vertical prop="title">
          <wd-input
            v-model="model.title"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：村子东边主路及垃圾桶状况亟待改善"
          />
        </wd-cell>
        <wd-cell title="情况描述" vertical prop="content">
          <wd-textarea
            v-model="model.content"
            :maxlength="300"
            :show-word-limit="true"
            placeholder="例如：我发现咱们村子东边的那条主路有好几处坑洼，已经存在很长时间了，一到下雨天就积水严重，给大家的出行带来很大不便。而且路边的一些垃圾桶也有破损情况，导致垃圾经常散落一地，影响村子的整洁卫生。希望村里能尽快解决这些问题，让我们的生活环境更加美好。"
          />
        </wd-cell>
        <wd-cell title="上传材料（图片）" vertical>
          <wd-upload
            :file-list="model.imgList"
            multiple
            name="file"
            image-mode="aspectFill"
            :action="actions"
            @change="handleFileChange"
            @success="handleChange"
            @remove="handleRemove"
            class="bg-#fff"
          ></wd-upload>
        </wd-cell>
        <wd-cell title="上传材料（视频）" vertical>
          <view class="flex">
            <template v-if="model.videoList.length >= 0">
              <view class="relative mr-12px" v-for="(item, index) in model.videoList" :key="index">
                <video :src="item.url" class="w-80px h-80px relative"></video>
                <view class="top--10px pos-absolute right--5px w-16px h-16px">
                  <!-- <img src="../../static/images/close.png" class="w-100% h-100%" /> -->
                  <wd-icon
                    name="error-fill"
                    size="16px"
                    custom-class="wd-upload__close"
                    @click="deleteVideo(index)"
                  ></wd-icon>
                </view>
              </view>
            </template>
            <view @click="handleVideo" class="pos-relative">
              <view class="w-80px h-80px flex justify-center items-center videoCard">
                <wd-icon size="35px" color="#B8B8B8" name="fill-camera"></wd-icon>
              </view>
            </view>
          </view>
        </wd-cell>
      </wd-form>
      <view class="w-100% px-80rpx box-border mt-60rpx">
        <wd-button block @click="submitHandler" :disabled="showButton">提交</wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { FormRules } from 'wot-design-uni/components/wd-form/types'
import { useToast } from 'wot-design-uni'
import { reportCreateAPI } from '@/service/VillageCondition/index'
import { useUserStore } from '@/store'
import _ from 'lodash'
const reportType = ref(1)
const userStore = useUserStore()
const toast = useToast()
const baseurl = ref(import.meta.env.VITE_SERVER_BASEURL)
const actions: string = baseurl.value + '/app-api/infra/file/business/upload'
const form = ref()
const showButton = ref(false)
const model = reactive<{
  title: string
  content: string
  files: any[]
  imgList: any[]
  videoList: any[]
}>({
  title: '',
  content: '',
  files: [],
  imgList: [],
  videoList: [],
})
const compress = true
const rules: FormRules = {
  title: [
    {
      required: true,
      message: '请输入标题',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入标题'))
        }
      },
    },
  ],
  content: [
    {
      required: true,
      message: '请输入情况描述',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入情况描述'))
        }
      },
    },
  ],
}
defineOptions({
  name: 'VillageConditionSub',
})
const residentId = computed(() => userStore.userInfo.residentId)
const residentType = computed(() => userStore.userInfo.type)
const gridMemberId = computed(() => userStore.userInfo.gridMemberId)
function handleChange({ file }) {
  const { response } = file
  const code = JSON.parse(response).code
  if (code != -1) {
    const fileId = JSON.parse(response).data.id
    file.fileId = fileId
    model.imgList.push(file)
  } else {
    model.imgList = [...model.imgList]
    toast.error({ msg: '图片违规', duration: 2000 })
  }
}
function handleFileChange({ fileList }) {
  //   model.fileList = fileList
}
function handleRemove({ file }) {
  model.imgList = model.imgList.filter((item) => {
    return item.uid !== file.uid
  })
}
function handleVideo() {
  uni.chooseVideo({
    maxDuration: 60, // 最大为60秒
    count: 1,
    compressed: true,
    camera: 'back',
    sourceType: ['album', 'camera'],
    success: (res) => {
      const videoFile = res.tempFilePath
      if (compress && res.size / 10240 > 1025) {
        console.log('压缩')
        videoCompress(res.tempFilePath)
        console.log('压缩后')
      } else {
        videoUpload(res.tempFilePath)
      }
    },
  })
}
const submitHandler = _.debounce(() => {
  handleSubmit()
}, 1000)
const handleSubmit = () => {
  const arr = [...model.imgList, ...model.videoList]
  model.files = arr.map((item) => {
    return item.fileId
  })
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        const creatorVo = {
          id: null,
          type: null,
        }
        if (residentType.value === 'cadre') {
          creatorVo.id = gridMemberId.value
          creatorVo.type = '1'
        } else {
          creatorVo.id = residentId.value
          creatorVo.type = '2'
        }
        try {
          reportCreateAPI({
            ...model,
            imgList: undefined,
            videoList: undefined,
            creatorVo,
            status: 1,
            type: reportType.value,
          }).then((res) => {
            toast.success({
              msg: '操作成功',
              duration: 0,
            })
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              })
              toast.close()
            }, 1000)
          })
        } catch (error) {
          console.log(error)
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

function videoCompress(tempFilePath) {
  toast.loading({
    msg: '压缩中...',
  })
  showButton.value = true
  uni.compressVideo({
    src: tempFilePath,
    quality: 'low', // 'low':低，'medium':中，'high':高
    success: function (res) {
      console.log('压缩后', res)
      showButton.value = false
      videoUpload(res.tempFilePath)
    },
    fail: function () {
      showButton.value = false
      toast.error({
        msg: '视频压缩失败',
      })
    },
    complete: () => {},
  })
}
function videoUpload(tempFilePath) {
  toast.loading({
    msg: '上传中...',
  })
  showButton.value = true
  const uploadTask = uni.uploadFile({
    url: '/app-api/infra/file/business/upload', // 自己文件上传的路径
    method: 'POST',
    filePath: tempFilePath,
    name: 'file',
    success: (res) => {
      const { data } = JSON.parse(res.data)
      data.url = baseurl.value + data.url
      data.fileId = data.id
      model.videoList.push(data)
      if (JSON.parse(res.data).data) {
        toast.success({
          msg: '上传成功',
        })
      }
    },
    fail: (err) => {
      toast.close()
      toast.error({
        msg: err + '',
      })
    },
    complete: () => {
      showButton.value = false
    },
  })
  uploadTask.onProgressUpdate((res) => {
    toast.loading({
      msg: '上传中' + res.progress + '%',
    })
    if (res.progress === 100) {
      toast.close()
    }
  })
}
function deleteVideo(index) {
  model.videoList.splice(index, 1)
}
// 测试 uni API 自动引入
onLoad(({ type }) => {
  reportType.value = type
})
</script>

<style lang="scss" scoped>
.videoCard {
  background: rgba(0, 0, 0, 0.04);
}
::v-deep .wd-icon-sound {
  margin-right: 20rpx;
}
::v-deep .wd-textarea {
  padding: 0 !important;
}
::v-deep .wd-textarea::after,
::v-deep .wd-input::after {
  height: 0 !important;
}

::v-deep .wd-textarea__value,
::v-deep .wd-input__value {
  padding: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-textarea__count,
::v-deep .wd-input__count {
  right: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-cell__title {
  font-weight: bold !important;
  color: #333 !important;
}
::v-deep .wd-cell__right {
  margin-top: 20rpx !important;
}
::v-deep .wd-button {
  background: #029669 !important;
}
</style>
